﻿using MySql.Data.MySqlClient;
using OF.Lib.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient; 
using System.Linq;
using System.Text;

namespace OF.Lib.DataAccess.Core
{
    public static class DbConnFactory
    {

        public static IDbConnection GetDbConnection(string sqlKey, out string sqlStr, out int timeOut)
        {
            SQL sqlConfig = SQLConfigHelper.GetSQL(sqlKey);
            DBGroup groupConfig = DBConfigHelper.GetDBGroup(sqlConfig.ConnKey);

            //预留工厂方法，可以取不同的Slave服务器群的负载实现方式
            IDbConnConfig dbConnConfigFactory = new DbConnConfigRandomImpl();
            DBConn dbConnConfig = dbConnConfigFactory.GetDbConnConfig(sqlConfig, groupConfig);

            timeOut = 60;
            sqlStr = sqlConfig.Text;
            if (sqlConfig.TimeOut > 0)
            {
                timeOut = sqlConfig.TimeOut;
            }
            else
            {
                if (dbConnConfig.TimeOut > 0)
                {
                    timeOut = dbConnConfig.TimeOut;
                }
            }
            IDbConnection dbConn = GetDbConnection(groupConfig.DBType, dbConnConfig.ConnStr);
            return dbConn;
        }

        public static IDbConnection GetDbConnection(string connKey, bool isMasterDB, out int timeOut)
        {
            DBGroup groupConfig = DBConfigHelper.GetDBGroup(connKey);
            //预留工厂方法，可以取不同的Slave服务器群的负载实现方式
            IDbConnConfig dbConnConfigFactory = new DbConnConfigRandomImpl();
            DBConn dbConnConfig = dbConnConfigFactory.GetDbConnConfig(isMasterDB, groupConfig);

            timeOut = 60;
            if (dbConnConfig.TimeOut > 0)
            {
                timeOut = dbConnConfig.TimeOut;
            }
            IDbConnection dbConn = GetDbConnection(groupConfig.DBType, dbConnConfig.ConnStr);            
            return dbConn;
        }



        internal static IDbConnection GetDbConnection(string dbType, string connStr)
        {
            IDbConnection dbConn = null;
            switch (dbType.Trim().ToUpper())
            {
                case "SQLSERVER":
                    dbConn = new SqlConnection(connStr);
                    break;
                case "MYSQL":
                    dbConn = new MySqlConnection(connStr);
                    break;
                case "ORACLE":
                    dbConn = new OleDbConnection(connStr);
                    break;
                default:
                    throw new Exception(string.Format("[GetDbConnection-not support]OF.Lib.DataAccess support only sqlserver,sqllite,mysql,oracle, this \"{0}\" dbtype can not support! ", dbType));
            }
            return dbConn;
        }

    }
}
